package com.jia.together.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jia.together.entity.Category;
import com.jia.together.entity.Resource;
import com.jia.together.mapper.ResourceMapper;
import com.jia.together.service.CategoryService;
import com.jia.together.service.ResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dujiajia
 * @since 2021-02-19
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    @Autowired
    private CategoryService categoryService;
    @Override
    public Map<String, Object> selectPageList(Long pageNum, Long pageSize) {

        Page<Resource> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Resource> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_create");
        Page<Resource> resourcePage = baseMapper.selectPage(page, wrapper);
        List<Resource> records = resourcePage.getRecords();
        long total = resourcePage.getTotal();
        Map<String,Object> map = new HashMap<>();
        map.put("records",records);
        map.put("total",total);
        return map;
    }

    @Override
    public Resource selectInfoById(String id) {
        Resource resource = baseMapper.selectById(id);
        Category category = categoryService.getById(resource.getCategoryId());
        resource.setCategoryName(category.getTitle());
        return resource;
    }

    @Override
    public Map<String, Object> queryList(String key, String categoryId, Long pageNum, Long pageSize) {
        Page<Resource> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Resource> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            wrapper.like("title",key);
        }
        if (!StringUtils.isEmpty(categoryId)){
            wrapper.eq("category_id",categoryId);
        }
        wrapper.eq("status",1);
        wrapper.orderByAsc("sort");
        Page<Resource> pages = baseMapper.selectPage(page, wrapper);
        List<Resource> records = pages.getRecords();
        long total = pages.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("records",records);
        map.put("total",total);
        return map;
    }
}
